package qa.tests;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.commons.io.IOUtils;

/**
 * Singleton that is responsible for writing the statistics to a file. The location of
 * the file is stated in a file called {@value #PROPERTY_FILENAME}
 * that should be located on the class path.
 * In case of the <code>test-test-maven-plugin</code> this is the plugin
 * that creates this file.
 * 
 * One should obtain instances of this writer using the {@link #instance()} method.
 */
public class StatisticsWriter {
    /**
     * Name of the file that indicates what the output directory is for writing
     * the file containing the satistics per method. 
     */
    public static final String PROPERTY_FILENAME = "__assert-counter.properties";
    /**
     * The single instance of this writer.
     */
    private static final StatisticsWriter instance = new StatisticsWriter();
    private File outputDirectory;
    
    private StatisticsWriter() {
        InputStream inputStream = getClass().getResourceAsStream("/" + PROPERTY_FILENAME);
        if(inputStream != null) {
            List<String> lines = null; 
            try {
                lines = IOUtils.readLines(inputStream);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            init(new File(lines.get(0)));
        }
    }
    public static StatisticsWriter instance() {
        return instance;
    }
    
    public synchronized void init(File outputDirectory) {
        this.outputDirectory = outputDirectory;
        outputDirectory.mkdirs();
        if(!outputDirectory.exists()) {
            throw new IllegalStateException("Directory " + outputDirectory.getAbsolutePath() + " does not exist and can not be created.");
        }
    }

    public void write(Statistics statistics) {
        if(outputDirectory == null) {
            throw new IllegalStateException("output directory for StatisticsWriter not set. You need to call init(File) before the asserts are counted.");
        }
        statistics.writeToFile(outputDirectory);
    }
    
    
}
